<template>
  <div style="position: relative; width: 100vw" :style="{ height: styleHeight + 'px', top: !mobile ? '60px' : '0' }">
    <el-card v-if="!resShow" class="card" :style="{ width: cardWidth + '%' }">
      <!-- <template #header>
                <div class="card-header">
                    <el-page-header @back="goBack" style="color: #ecf5ff">
                        <template #content><span class="text-large font-600 mr-3" style="color: #ecf5ff">
                                完善企业信息
                            </span></template>
                    </el-page-header>
                </div>
            </template> -->
      <div class="div-msg">提示：检测到当前账号未完善企业信息，且密码为弱口令，请进行完善相关信息后进入操作页面！</div>
      <div class="div_form" :style="{ height: styleHeight - 100 + 'px' }">
        <el-form
          ref="corpFormRef"
          v-loading="loading"
          :model="corpForm"
          :rules="rules"
          label-width="180px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
          autocomplete="off"
        >
          <!-- 数据部分 -->
          <el-row justify="start">
            <el-col :span="itemSpan">
              <el-form-item label="企业名称" prop="name">
                <el-input v-model="corpForm.name" :disabled="true" placeholder="请输入企业名称" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="企业分类" prop="corpType">
                <el-select v-model="corpForm.corpType" placeholder="请选择" clearable>
                  <el-option v-for="item in corpTypes" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="企业单位类型" prop="type">
                <el-select v-model="corpForm.type" placeholder="请选择" clearable>
                  <el-option
                    v-for="item in constructorTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="企业信用代码" prop="code">
                <el-input v-model="corpForm.code" :disabled="true" placeholder="请输入企业信用代码" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="企业注册地" prop="areaCode">
                <el-cascader
                  v-model="corpForm.areaCode"
                  placeholder="请选择"
                  :options="areaoptions"
                  class="custom-cascader"
                  @change="handleCascaderChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="法人姓名" prop="legalman">
                <el-input v-model="corpForm.legalman" placeholder="请输入法人姓名" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="法人身份证号码" prop="legalCardno">
                <el-input v-model="corpForm.legalCardno" placeholder="请输入法人身份证号码" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="法人手机号码" prop="legalMobile">
                <el-input v-model="corpForm.legalMobile" placeholder="请输入法人手机号码" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="企业注册日期" prop="registerDate">
                <el-date-picker
                  v-model="corpForm.registerDate"
                  type="date"
                  placeholder="选择企业注册日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="date-picker"
                />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="联系人" prop="linkMan">
                <el-input v-model="corpForm.linkMan" placeholder="请输入联系人" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="联系人电话" prop="linkTel">
                <el-input v-model="corpForm.linkTel" placeholder="请输入联系人电话" class="input300" />
                <el-button
                  type="success"
                  style="position: absolute; right: -50px"
                  plain
                  :disabled="disCode"
                  @click="tryCode"
                  >{{ codeBtn }}</el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="验证码" prop="verificationCode">
                <el-input v-model="corpForm.verificationCode" placeholder="请输入验证码" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="注册地址" prop="regAddr">
                <el-input v-model="corpForm.regAddr" placeholder="请输入注册地址" />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="办公地址" prop="officeAddr">
                <el-input v-model="corpForm.officeAddr" placeholder="请输入办公地址" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="经济类型" prop="economicType">
                <el-select v-model="corpForm.economicType" placeholder="请选择经济类型" clearable>
                  <el-option
                    v-for="item in economicTypeoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="法人职务" prop="legalTitle">
                <el-select v-model="corpForm.legalTitle" placeholder="请选择法人职务" clearable filterable>
                  <el-option v-for="item in legalTitles" :key="item.label" :label="item.label" :value="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="法人职称" prop="legalDuty">
                <el-select v-model="corpForm.legalDuty" placeholder="请选择法人职称" clearable>
                  <el-option v-for="item in legalDutys" :key="item.label" :label="item.label" :value="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="注册资本" prop="regCapital">
                <money-input v-model="corpForm.regCapital" unit="万元" class="input300"></money-input>
                <!-- <el-input v-model="corpForm.regCapital" placeholder="请输入注册资本" class="input300" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="邮编" prop="zipCode">
                <el-input v-model="corpForm.zipCode" placeholder="请输入邮编" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="登录密码" prop="password">
                <!-- <el-input v-model="corpForm.password" type="password" placeholder="请输入登录密码" class="input300" /> -->
                <PasswordInput ref="passwordInputRef" class="input300" @input-change="handlePasswordChange" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="corpForm.confirmPassword"
                  type="password"
                  placeholder="请输入确认密码"
                  class="input300"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item label="上传营业执照、资质证书" prop="attachments">
              <el-upload
                v-model:file-list="fileList"
                :action="actionUrl"
                multiple
                :limit="5"
                accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
                :on-exceed="handleUploadExceed"
                :on-success="handleUploadSuccess"
                :on-preview="handleUploadPreview"
              >
                <el-button plain size="small">上传附件</el-button>
                <template #tip>
                  <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="display: flex; align-item: center; justify-content: center">
            <el-button
              v-loading="loading"
              type="primary"
              size="large"
              style="width: 100px; margin-top: 30px"
              @click.prevent="submit"
            >
              下一步
            </el-button>
          </el-col>
        </el-form>
      </div>
    </el-card>
    <resComponent v-else style="margin-top: 200px"></resComponent>
  </div>
</template>

<script lang="ts" setup>
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
import MoneyInput from "@/components/MoneyInput/index.vue";
import PasswordInput from "@/components/PasswordInput/index.vue";
import { corpLogin, getCorpInfo } from "@/api/account/corp/index";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules, UploadUserFile } from "element-plus";
import { CorpForm } from "@/api/account/corp/types";
import { getDicts } from "@/store/modules/dict";
import { LocationQuery, LocationQueryValue, useRouter, useRoute } from "vue-router";
import resComponent from "@/views/account/register/resComponent/index.vue";
import { isMobile } from "@/utils";
import { useScreen } from "@/store/modules/screen";
import { useAppStore } from "@/store/modules/app";
import { initCustomFormatter } from "vue";
import { getVerificationCode } from "@/api/account/project/index";
import { Except, Ride } from "@/utils/decimal";

const codeBtn = ref("获取验证码");
const codeCount = ref(60);
const disCode = ref(false);

const screenStore = useScreen();
const appStore = useAppStore();
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const resShow = ref(false);
const corpTypes = getDicts("corpTypes");
const corpEconomicTypes = getDicts("corpEconomicTypes");
const constructorTypes = getDicts("constructorTypes");
const formSize = ref("");
const itemSpan = ref(8);
const mobile = ref(false);
const styleHeight = ref(600);
const cardWidth = ref(80);
const token = useStorage("accessToken", "");
const corpForm = reactive<CorpForm>({});
// const corpForm = ref(reactive<CorpForm>)
const corpFormRef = ref(ElForm); // 表单/清空重置使用
let codeInterval = ref();
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传营业执照、资质证书!"));
    return;
  } else {
    callback();
  }
};

const rules = reactive<FormRules<CorpForm>>({
  name: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],
  password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
  provinceCode: [{ required: true, message: "归属省不能为空", trigger: "blur" }],
  cityCode: [{ required: true, message: "归属地市不能为空", trigger: "blur" }],
  areaCode: [{ required: true, message: "归属区县不能为空", trigger: "blur" }],
  regAddr: [{ required: true, message: "注册地址不能为空", trigger: "blur" }],
  legalman: [{ required: true, message: "法人姓名不能为空", trigger: "blur" }],
  legalDuty: [{ required: true, message: "法人职称不能为空", trigger: "blur" }],
  officeAddr: [{ required: true, message: "办公地址不能为空", trigger: "blur" }],
  economicType: [{ required: true, message: "请选择经济类型", trigger: "blur" }],
  type: [{ required: true, message: "请选择企业单位类型", trigger: "blur" }],
  legalCardno: [
    { required: true, message: "法人身份证号码不能为空", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号码",
      trigger: "blur",
    },
  ],
  legalMobile: [
    { required: true, message: "法人手机号码不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  registerDate: [{ required: true, message: "企业注册日期不能为空", trigger: "blur" }],
  linkMan: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  legalTitle: [{ required: true, message: "法人职务不能为空", trigger: "blur" }],
  linkTel: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  attachments: [
    {
      required: true,
      message: "请上传营业执照、资质证书",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
  confirmPassword: [{ required: true, trigger: "blur", validator: passwordBlur }],
});

if (isMobile()) {
  mobile.value = true;
  itemSpan.value = 24;
  styleHeight.value = screenStore.screenHeight;
  cardWidth.value = 100;
} else {
  styleHeight.value = 750;
  cardWidth.value = 80;
  itemSpan.value = 8;
}

//返回上一页
const goBack = () => {
  router.go(-1);
};

function tryCode() {
  if (!corpForm.linkTel) {
    ElMessage.warning("请输入手机号码");
    return;
  }
  let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!reg.test(corpForm.linkTel)) {
    ElMessage.warning("请输入正确的手机号码");
    return;
  }
  getCode();
}

const getCode = useThrottleFn(async () => {
  btnToDis();
  let code = await getVerificationCode(corpForm.linkTel ?? "");
  if (code.success) {
    ElMessage.success("验证码发送成功!");
  } else {
    ElMessage.error(code.msg);
    disCode.value = false;
    codeCount.value = 60;
    codeBtn.value = "获取验证码";
    clearInterval(codeInterval.value);
  }
}, 3000);

function btnToDis() {
  disCode.value = true;
  codeInterval.value = setInterval(() => {
    if (codeCount.value > 0) {
      codeCount.value--;
      codeBtn.value = `重新获取 (${codeCount.value})`;
    } else {
      disCode.value = false;
      codeCount.value = 60;
      codeBtn.value = "获取验证码";
      clearInterval(codeInterval.value);
    }
  }, 1000);
}
function initForm() {
  getCorpInfo(route.query.editToken).then((res) => {
    if (res.success === true) {
      corpForm.editToken = route.query.editToken;
      corpForm.regCapital = Except(res.data.regCapital, 10000);
      Object.assign(corpForm, res.data);
    }
  });
}

function passwordBlur(rule: any, value: any, callback: any) {
  if (!value || value === undefined || value === "") {
    callback(new Error("确认密码不能为空"));
    return;
  } else {
    if (value != corpForm.password) {
      callback(new Error("两次密码不一致"));
      return;
    } else {
      callback();
    }
  }
}
const allowPassword = ref(false);
const handlePasswordChange = (value: any, allow: boolean) => {
  corpForm.password = value;
  allowPassword.value = allow;
};
/**
 * 表单提交
 */
const submit = useThrottleFn(() => {
  if (!allowPassword.value) {
    return;
  }
  corpFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        let attachments = new Array();
        fileList.value.forEach((item) => {
          if (item.status === "success") {
            if (item.response) {
              attachments.push({
                attachmentId: item.response.data,
              });
            }
          }
        });
        corpForm.attachments = attachments;
      }
      let submitForm = Object.assign({}, corpForm);
      submitForm.regCapital = Ride(corpForm?.regCapital ?? 0, 10000);
      corpLogin(submitForm)
        .then((data) => {
          if (data.success) {
            const { tokenType, accessToken } = data.data;
            token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
            resShow.value = true;
            loading.value = false;
            // setTimeout(() => {
            //   loading.value = false;
            //   router.push({ path: "dashboard" }).then(() => {
            //     ElMessage.success("登录成功");
            //   });
            // }, 3000);
          } else {
            ElMessage({
              type: "error",
              message: data.msg,
            });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

function clearUp() {
  ElMessage.success("清空成功");
  corpFormRef.value.resetFields();
  corpFormRef.value.clearValidate();
}

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

const handleCascaderChange = (value: any) => {
  if (value.length == 3) {
    corpForm.provinceCode = value[0];
    corpForm.cityCode = value[1];
    corpForm.areaCode = value[2];
  }
  // 在这里可以对选中的值进行进一步处理
};

onMounted(() => {
  initForm();
});
const areaoptions = getDicts("areaTrees").filter((item: { value: number }) => item.value === 540000);
const economicTypeoptions = getDicts("corpEconomicTypes");
const legalDutys = getDicts("legalManTitleTypes");
const legalTitles = getDicts("legalManDutyTypes");
</script>
<style lang="scss" scoped>
.div_form {
  width: 100%;
  overflow: auto;
  // display: flex;
  // justify-content: center;
  // align-items: center;
}

.card {
  width: 80%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  background-color: #337ecc;
  align-items: center;
  padding: 10px;
}

:deep() .el-card__header {
  padding: 0px;
}

.demo-ruleForm {
  width: 100%;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  // flex-wrap: wrap;
  padding-top: 20px;
}

.div-felx {
  display: flex;
  justify-content: center;
}

.input300 {
  //width: 200px !important;
  width: 80%;
}

.el-select .el-input__inner {
  //width: 165px !important;
  width: 80% !important;
}

.date-picker {
  //width: 200px !important;
  width: 80% !important;
}

:deep() .el-date-editor {
  //width: 200px !important;
  width: 80% !important;
}

:deep() .el-cascader {
  //width: 200px !important;
  width: 80% !important;
}

:deep() .el-select {
  //width: 200px !important;
  width: 80% !important;
}

.custom-cascader {
  //width: 200px !important;
  width: 80% !important;
}

.div-msg {
  text-align: center;
  margin: auto;
  line-height: 48px;
  color: red;
  font-size: 16px;
}
</style>
